package cn.client.ui.view.main.user

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import androidx.hilt.navigation.compose.hiltViewModel
import cn.client.data.remoteData.bean.DateUtils
import kotlinx.coroutines.launch

/**
 * 修改用户信息页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UserInfoEdit(
    userId: Int,
    viewModel: UserInfoViewModel = hiltViewModel()
) {
    // 性别选择
    val genders = listOf("男", "女")
    var selectedGender by remember { mutableStateOf(genders[0]) } // 初始化为"男"
    var expanded by remember { mutableStateOf(false) }
    // 生日选择
    var openDialog by remember { mutableStateOf(false) }
    val datePickerState = rememberDatePickerState()
    val confirmEnabled = derivedStateOf { datePickerState.selectedDateMillis != null }

    // 协程
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current

    var userName: String by remember { mutableStateOf("")}
    var currentArea: String by remember { mutableStateOf("")}

    val userGender = { gender: String ->
        when (gender) {
            "男" -> 1
            "女" -> 2
            else -> 0
        }
    }
    // 使用 remember 来存储转换后的日期字符串
    val selectedDateText  = remember { mutableStateOf<String?>(null) }

    coroutineScope.launch {
        datePickerState.selectedDateMillis?.let { it1 ->
            val dataString = DateUtils.dateToStr(it1)
            selectedDateText.value = dataString
        }
    }

    //  使用LaunchedEffect来启动协程，收集事件
    LaunchedEffect(Unit){
        viewModel.pageEvents.collect {
            if (it is UserInfoViewModel.PageEvent.EditUserInfo){
                if (it.res.code==200){
                    // 修改后再次获取用户信息
                    viewModel.dispatch(UserInfoViewModel.PageIntent.GetUserInfo(uid = userId))
                    Toast.makeText(context,"修改成功，信息：${it.res.msg}", Toast.LENGTH_LONG).show()
                } else {
                    Toast.makeText(context,"修改失败，信息：${it.res.msg}", Toast.LENGTH_LONG).show()
                }
            }
            if (it is UserInfoViewModel.PageEvent.Error){
                Toast.makeText(context,"修改失败，信息：${it.error}", Toast.LENGTH_LONG).show()
            }
        }
    }


    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ){
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(2.dp)
        ) {
            // 第一行：用户名 文本输入框
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
            ){
                OutlinedTextField(
                    value = userName,
                    onValueChange = { str -> userName = str},
                    label = { Text("用户名") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                )
            }
            // 第二行：性别 文本输入框
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(16.dp)
                    .border(
                        1.dp,
                        MaterialTheme.colorScheme.outline,
                        shape = RoundedCornerShape(6.dp)
                    )
            ){
                TextButton(onClick = { expanded = !expanded }) {
                    Text(text = "性别：")
                    Text(text = selectedGender)
                    /* 下拉框 */
                    DropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = !expanded }, // 当下拉菜单展开/关闭时更新状态
                        modifier = Modifier.wrapContentSize(),
                        properties = PopupProperties(
                            focusable = true,
                            dismissOnBackPress = false,
                            dismissOnClickOutside = true
                        )
                    ) {
                        genders.forEach { gender ->
                            DropdownMenuItem(
                                { Text(text = gender) },
                                onClick = {
                                    selectedGender = gender
                                    expanded = false // 点击菜单项后关闭下拉菜单
                                }
                            )
                        }
                    }
                }
            }
            // 第三行：生日 日期选择器
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(16.dp)
                    .border(
                        1.dp,
                        MaterialTheme.colorScheme.outline,
                        shape = RoundedCornerShape(6.dp)
                    )
            ){
                Column(modifier = Modifier
                    .clickable {
                        openDialog = !openDialog
                    }) {
                    Text(text = "生日：${selectedDateText.value?:""}", modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp) )}
            }
            // 第四行：地区 输入框
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
            ){
                OutlinedTextField(
                    value = currentArea,
                    onValueChange = {  str -> currentArea = str },
                    label = { Text("地区") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                )
            }
            // 第五行：按钮 确认
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
            ){
                Button(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(10.dp),
                    onClick = {
                    /* 处理确认按钮点击 */
                        coroutineScope.launch {
                            viewModel.dispatch(UserInfoViewModel.PageIntent.EditUserInfo(
                                uid = userId,
                                uname = userName,
                                gender = userGender(selectedGender),
                                birthday = datePickerState.selectedDateMillis,
                                area = currentArea
                            ))
                        }
                    }
                ) {
                    Text("确认修改")
                }
            }
        }

    }


    /* 日期选择器 */
    if (openDialog) {
        DatePickerDialog(
            onDismissRequest = {
                openDialog = false
            },
            modifier = Modifier.fillMaxSize(),
            confirmButton = {
                TextButton(
                    onClick = {
                        openDialog = false
                        Log.d("UserInfoEdit","选中时间戳为： ${datePickerState.selectedDateMillis}")
                    },
                    enabled = confirmEnabled.value
                ) {Text("确定") } }, dismissButton = { TextButton( onClick = { openDialog = false } ) {Text("取消") } }
        ) {
            DatePicker(state = datePickerState)
        }
    }

}



//@OptIn(ExperimentalMaterial3Api::class)
//@Composable
//fun DateDialog(
//
//){
//    val openDialog = remember { mutableStateOf(true) }
//    if (openDialog.value) {
//        val datePickerState = rememberDatePickerState()
//        val confirmEnabled = derivedStateOf { datePickerState.selectedDateMillis != null }
//        DatePickerDialog(
//            onDismissRequest = {
//                openDialog.value = false
//            },
//            modifier = Modifier.fillMaxSize(),
//            confirmButton = {
//                TextButton(
//                    onClick = {
//                        openDialog.value = false
//                        Log.d("UserInfoEdit","选中时间戳为： ${datePickerState.selectedDateMillis}")
//                    },
//                    enabled = confirmEnabled.value
//                ) {Text("确定") } }, dismissButton = { TextButton( onClick = { openDialog.value = false } ) {Text("取消") } }
//        ) {
//            DatePicker(state = datePickerState)
//        }
//    }
//
//}



//@Composable
//fun GenderDropdown() {
//    // 性别选项
//    val genders = listOf("男", "女")
//
//    // 管理下拉菜单的展开/关闭状态
//    var expanded by remember { mutableStateOf(false) }
//
//    // 管理选择的性别
//    var selectedGender by remember { mutableStateOf(genders[0]) } // 初始化为"男"
//
//    DropdownMenu(
//        expanded = expanded,
//        onDismissRequest = { expanded = !expanded }, // 当下拉菜单展开/关闭时更新状态
//        modifier = Modifier.wrapContentSize(),
//        properties = PopupProperties(
//            focusable = true,
//            dismissOnBackPress = false,
//            dismissOnClickOutside = true
//        )
//    ) {
//        genders.forEach { gender ->
//            DropdownMenuItem(
//                { Text(text = gender) },
//                onClick = {
//                    selectedGender = gender
//                    expanded = false // 点击菜单项后关闭下拉菜单
//                }
//            )
//        }
//    }
//
//    // 可选的：显示当前选择的性别
//    Text(text = "当前选择的性别：${selectedGender}")
//}